<script setup>
import { NEW_FILE, OPEN_FILE, SAVE_FILE, OPEN_FOLDER } from '@msg/file.js'
import { ref, onMounted } from 'vue'

const { ipcRenderer } = window.electron
const $file = ref()
const $folder = ref()
const file = ref()
const fileContent = ref('')
const fileMenus = [
  { title: '新建文件', key: NEW_FILE },
  { title: '打开文件', key: OPEN_FILE },
  { title: '保存文件', key: SAVE_FILE },
  { title: '打开文件夹', key: OPEN_FOLDER }
]

onMounted(() => {
  ipcRenderer.on(`${OPEN_FILE}-render`, (e, data) => {
    fileContent.value = data.toString()
  })
})

const operateFile = (key) => {
  const eventMap = {
    [OPEN_FILE]: () => {
      $file.value.click()
    },
    [OPEN_FOLDER]: async () => {
      $folder.value.click()
    }
  }
  eventMap[key] && eventMap[key]()
}

const loadFile = (e) => {
  const { files } = e.target
  const { path } = files[0]
  console.log('path', files[0])
  ipcRenderer.send(OPEN_FILE, path)
}

const loadFolder = (e) => {
  const { files } = e.target
  const { webkitRelativePath, path } = files[0]
  const folderName = webkitRelativePath.split('/')[0]
  const pathArr = path.split('\\')
  const index = pathArr.findIndex((item) => item === folderName)
  const folderPath = pathArr.slice(0, index + 1).join('\\')
  ipcRenderer.send(OPEN_FOLDER, folderName, folderPath)
}

const saveFile = (e) => {
  console.log('folder', e)
}
</script>

<template>
  <div class="menu-wrap">
    <el-dropdown trigger="click" @command="operateFile">
      <span class="menu-tab"> 文件 </span>
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item v-for="(item, index) in fileMenus" :key="index" :command="item.key">
            {{ item.title }}
          </el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>

    <input type="file" v-show="false" ref="$file" @change="loadFile" />
    <input type="file" v-show="false" ref="$folder" @change="loadFolder" webkitdirectory />
  </div>
</template>

<style lang="scss" scoped>
.menu-tab {
  cursor: pointer;
  padding: 5px 10px;
  box-sizing: border-box;
  border-radius: 5px;
  border: 1px solid #000;
  &:hover {
    border-radius: 5px;
    border-color: #eee;
  }
}
</style>
